package utils

import (
	log "IEC104_Slave/clog"
	"encoding/json"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

/*
*
创建文件
*/
func saveJsonFile(fileName string, data interface{}) {
	log.MainLog.Infof("保存文件%v", fileName)
	marshal, err := json.Marshal(data)
	if err != nil {
		log.MainLog.Errorf("内容json化异常%v;%v", data, err)
		return
	}

	dirPath := "./generate"
	err = os.MkdirAll(dirPath, 0755)
	//if err != nil {
	//	if !os.IsExist(err) {
	//		log.MainLog.Errorf("创建目录 %s 失败：%v", dirPath, err)
	//		return
	//	}
	//	log.MainLog.Debug("目录 %s 已存在，无需创建", dirPath)
	//} else {
	//	log.MainLog.Infof("创建目录 %s 成功\n", dirPath)
	//}
	filePath := filepath.Join(dirPath, fileName)
	file, err := os.Create(filePath)
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			log.MainLog.Errorf("文件关闭异常%v;%v", filePath, err)
		}
	}(file)

	if err != nil {
		log.MainLog.Errorf("文件创建异常%v;%v", filePath, err)
		return
	}
	_, err = file.Write(marshal)
	if err != nil {
		log.MainLog.Errorf("文件写入异常%v;%v", filePath, err)
		return
	}
}

// SaveJsonFileNoName /*
func SaveJsonFileNoName(data interface{}) {
	fileName := "nio_setValue_" + strconv.FormatInt(time.Now().UnixNano()/1e6, 10) + ".json"
	saveJsonFile(fileName, data)
}
